import { Navigate, useLocation, useNavigate, useRoutes } from "react-router";
import { lazy, Suspense, useEffect, useMemo } from "react";
import LayoutPage from "@/pages/layout/LayoutPage";
import LoginPage from "@/pages/login";
import useSlicesData from "@/hooks/useSlicesData";
import type { RootState } from "@/store/store";
import { useSelector } from "react-redux";
import StaffForm from "@/pages/staff/roster/staffForm";

const NotFound = lazy(() => import('@/pages/404'))
const modules = import.meta.glob('/src/pages/**/*.tsx')
const WHITE_LIST = ['/login'];

const RouterConfig = () => {
    const location = useLocation();
    const adminInfo = useSelector((state: RootState) => state.admin.adminInfo)
    const { getAdminInfoHook } = useSlicesData();
    const navigate = useNavigate();

    useEffect(() => {
        // 判断当前的页面是否是白名单页面
        if (!WHITE_LIST.includes(location.pathname)) {
            // 如果不是白名单页面，说明需要权限才能访问
            const loginToken = localStorage.loginToken;
            if (loginToken) {
                // 发请求获取用户的权限数据
                getAdminInfoHook();
            } else {
                //未登录
                navigate('/login', { replace: true })
            }
        }
    }, [location])



    // 通过计算属性，计算出路由数组
    const router = useMemo(() => {
        return ([
            // 路由重定向
            {
                path: '/',
                element: <Navigate to='/home' />
            },
            {
                path: '/',
                Component: LayoutPage,
                // 二级路由
                children: [
                    ...getRoutes(adminInfo?.roleId?.permissions),
                    {
                        path: '/staff/staffManage/staffManage/add',
                        element: <StaffForm />
                    }
                ]
            },
            {
                path: '/login',
                element: <LoginPage />
            },
            // 404路由
            {
                path: '/*',
                // 路由懒加载
                element: (
                    <Suspense fallback={<p>玩命加载中......</p>}>
                        <NotFound />
                    </Suspense>
                )
            }
        ])
    }, [adminInfo])

    // 将路由数组传递给 useRoutes()方法，生成路由配置，返回给父组件
    return useRoutes(router)
}

export default RouterConfig;
// 遍历权限数组，将权限数据处理成路由数据
function getRoutes(data: any = []): any {
    return data.reduce((prev: any, item: any) => {
        if (item.component) {
            return [
                ...prev,
                // 路由对象 
                {
                    path: item.path,//路径
                    element: lazyLoadComponent(item.component)//组件
                },
                ...getRoutes(item.children)
            ]
        }
        return [
            ...prev,
            ...getRoutes(item.children)
        ]
    }, [])

}

// 接收一个组件路径作为参数，根据组件路径动态加载对应的组件
function lazyLoadComponent(componentPath: string) {
    // 拼接组件路径，获取到组件的 () => import() 函数
    const importComponent: any = modules[`/src/pages${componentPath}.tsx`];
    if (importComponent) {
        // 如果能获取到组件的() => import()函数，就将该函数传递给lazy()进行组件懒加载
        const LazyComponent = lazy(importComponent);
        return (
            <Suspense>
                <LazyComponent />
            </Suspense>
        )
    }
    return null;
}

